<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="content">APP发送过来的数据:</div>
    <input id="messageInput" placeholder="输入信息后app即可展示" type="text">
</body>
<script>
    let contentDiv = document.getElementById("content")
    let messageInput = document.getElementById("messageInput")

    // 处理app发来的信息
    const appMessageHandle = event => {
        console.log("接收app信息");
        const message = event.data
        if (typeof message === 'string') {
            contentDiv.innerText = "APP发送过来的数据: " + message
        }
    }

    // 与app的通信对象
    let appPort = undefined
    // 监听app那边的挂载事件
    window.addEventListener('message', event => {
        if (event.data === '__init_port__') {
            appPort = event.ports[0]
            if (appPort) {
                console.log("挂载port");
                appPort.onmessage = appMessageHandle

                // 监听input输入与app通信
                messageInput.addEventListener("input", event => {
                    const inputValue = event.target.value
                    console.log("发送信息给APP " + inputValue);
                    appPort.postMessage(inputValue)
                })
            }
        }
    })
</script>

</html>